/*Hita0WssSbjpM+C19QDJ07Polf/ANXjrTbPQimCg5mSCg+tCWtORC5TxqS/esH2V*/
/**
 * 卡片 card_head 区域按钮的事件处理
 */
 import ampub from 'ampub';
import fa from 'fa';
import moment from 'moment';
import { ajax, cardCache, output, print, toast, base } from 'nc-lightapp-front';
import CreateNCUploade from 'uap/common/components/CreateNCUploade';
import { isFunction } from '../../../../public/util/tools';
import constants from '../../constants';
import afterEvent from './afterEvent';
import { rentPayPlanButtonClick } from './index';
import initTemplate from './initTemplate';
import pageInfoClick from './pageInfoClick';
import { updateDeptRefLevel } from './refFilter';
import setStatus from './setStatus';
import {
    getUsufructAssetTab
} from './usufructAssetHandler';
import { updateAssetGroupItem, updateDeptmethodItem } from './utils';
import { ORGID, SYSINIT } from '../../../../../arap/common/constant';


 const { createNCUploader, show: ncUploaderShow, close: ncUploaderClose } = CreateNCUploade;
const {
	components: {
		LoginContext: { getContext, loginContextKeys },
		queryAboutUtils: { openEquipCardByPk, openEquipCardByFaCardPk },
		queryVocherUtils: { queryAboutVoucher, openToVouchar },
         	saveValidatorsUtil: {beforeSaveValidator }
	},
	utils: { multiLangUtils: { getMultiLangByID }, msgUtils: { showConfirm, MsgConst, showMessage, showErrorMessageByRes } }
} = ampub;

const {
	fa_components: { CardLinkToBillUtil: { CardLinkToBill }, ImageMng: { cardFaImageView, cardFaImageScan } },
	fa_utils: { metaUtil }
} = fa;

const {
	PAGE_CODE,
	TabsHideDefault,
	MODAL_ID,
	DATA_STATUS,
	URL,
	UISTATE,
	VOSTATUS,
	BILL_SOURCE_TYPES,
	ASSET_ADDED_WAY,
	FIELDS,
	assetDataSource,
	AREA: {
		CARD: {
			BASIC_INFO_AREA: basicInfoForm,
			FINANCE_AREA: financeForm,
			USEDEPT_TAB: usedept_tab,
			LRZX_TAB: lrzx_tab,
             		DEP_TAB: dep_tab,
			SUBEQUIP_TAB: subequip_tab,
			ASSET_ALL: assetAllArea,
			USUFRUCTASSET_AREA: usufructassetForm,
			RENTPAYPLAN_TAB: rentpayplan_tab,
			DEPACCRUAL_TAB: depaccrual_tab,
			STEPRENTSTANDARD_TAB: steprentstandard_tab,
			LOGDEPACCRUAL_TAB: logdepaccrual_tab,
			LOGCHANGERECORD_TAB: logchangerecord_tab,
			DEPACCRUAL_TAB_MONTH: depaccrual_tab_month,
			EVALUATE_TAB: evaluate_tab,
			DEVALUE_TAB: devalue_tab,
			ALTER_TAB: alter_tab,
			REDUCE_TAB: reduce_tab,
			DEPLOY_TAB: deploy_tab
		}
	},
	CARD_BTNS: {
		TABLE_HEAD,
		HEAD: {
			ADD,
			EDIT,
			DELETE,
			SAVE,
			SaveAdd,
			CANCEL,
			REFRESH,
			COPY,
			SimulateDep,
			SimulateAccudep,
			PRINT_CHILD,
			PRINT_NOCHILD,
			Output,
			QueryAboutCard,
			QueryAboutVoucher,
			FABillQueryAboutVoucher,
			QueryAboutBusiness,
			Attachment,
			FAReceiptShow,
			FAReceiptScan,
			LEASELIABILITIES
		}
	}
} = constants;

export default function(props, id) {
	const that = this;
	switch (id) {
		//修改按钮
		case EDIT:
			doEdit(that);
			break;

		case DELETE:
			showConfirm.call(this, props, {
				type: MsgConst.Type.Delete,
				beSureBtnClick: () => {
					doDelete(that);
				}
			});
			break;

		case SAVE:
			doSave(that);
			break;

		case SaveAdd:
			doSaveAdd(that);
			break;

		case COPY:
			doCopy(that);
			break;

		case PRINT_CHILD:
			doPrintChild(that);
			break;

		case PRINT_NOCHILD:
			doPrintNoChild(that);
			break;

		case Output:
			doOutput(that);
			break;

		case CANCEL:
			showConfirm.call(this, props, {
				type: MsgConst.Type.Cancel,
				beSureBtnClick: () => {
					doCancel(that);
				}
			});

			break;

		case REFRESH:
			doRefresh(that);
			break;

		//模拟折旧
		case SimulateDep:
			doSimulateDep(that);
			break;

		//模拟累计折旧
		case SimulateAccudep:
			doSimulateAccudep(that);
			break;

		//联查设备卡片
		case QueryAboutCard:
			queryAboutCard(that.props);
			break;

		//附件
		case Attachment:
			attachment.call(this, that.props);
			break;

		// 影像扫描
		case FAReceiptScan:
			faReceiptScan.call(this, props);
			break;

		// 影像查看
		case FAReceiptShow:
			faReceiptShow.call(this, props);
			break;

		//来源单据
		case QueryAboutBusiness:
			billreview.call(that);
			break;

		//联查凭证
		case QueryAboutVoucher:
			// tableId为区域编码，第三个参数为主键编码，appcode为应用编码,新增参数，标志列表态联查
			const { props: { pageConfig: { appid: appcode } } } = this;
			queryAboutVoucher(props, basicInfoForm, 'pk_card', appcode);
			break;

		//联查业务凭证
		case FABillQueryAboutVoucher:
			faBillQueryAboutVoucher(that);
			break;

		//计算租赁负债
		case LEASELIABILITIES:
			calculateLeaseLiabilities.call(this);
			break;

		// 租赁变更
		case TABLE_HEAD.LEASE_CHANGE:
			rentPayPlanButtonClick.call(this, this.props, TABLE_HEAD.LEASE_CHANGE);
			break;

		//卡片交易类型按钮点击
		default:
			doAdd(that, id);
			break;
	}
}

//新增-点击新增下的交易类型按钮
function doAdd(that, id) {
	that.resetOnAdd();
	that.props.setUrlParam({
		transiType: id,
		pagecode: id,
		status: UISTATE.ADD,
		id: '' //id（pk）置空
	});
	//交易类型改变，需要刷新当前页
	initTemplate.call(that, that.props).then(() => {
		that.financeOrgInit();
		setStatus.call(that, that.props);
	});
}

//保存前
function saveBefore() {
	//校验是否存在账簿数据
	let valid = this.state.accbooks && this.state.accbooks.length;
	if (!valid) {
		/*国际化处理：没有可用的资产账簿*/
		showMessage(null, { content: getMultiLangByID('201201504A-000003'), color: 'warning' });
		return valid;
	}
	return checkNull.call(this);
}

/**
 * 校验阶梯租金必输项
 */
function checkStepRentTable() {
	const { props, props: { form, cardTable } } = this;

	cardTable.filterEmptyRows(steprentstandard_tab, [ 'start_date' ]);

	let steprentstandardrows = cardTable.getVisibleRows(steprentstandard_tab);
	if (!steprentstandardrows || steprentstandardrows.length == 0) {
		toast({
			color: 'error',
			content: getMultiLangByID('201201504A-0000111') /*国际化处理：请录入阶梯租金标准！*/
		});
		return false;
	}

	//阶梯租金标准
	let tab_check = cardTable.checkTableRequired(steprentstandard_tab);
	if (!tab_check) {
		return false;
	}

	return true;
}

//前端进行非空校验
function checkNull() {
	const { props, props: { form, cardTable }, state: { financeShowFlag } } = this;
	//表头必输项校验
	let checkResult = form.isCheckNow([ basicInfoForm ]);
	if (!checkResult) {
		return false;
	}

	// 检查财务form是否存在
	if (financeShowFlag) {
		let checkResultFinanceForm = form.isCheckNow([ financeForm ]);
		if (!checkResultFinanceForm) {
			return false;
		}
	}

	// 检查使用权form是否存在
	let usufructasset_flag = form.getFormItemsValue(basicInfoForm, 'usufructasset_flag').value;
	if (usufructasset_flag) {
		//表头必输项校验
		let check_flag = form.isCheckNow([ basicInfoForm ]);
		if (!check_flag) {
			return false;
		}
		if (this.isNeedCalculateLeaseLiabilities) {
			toast({
				color: 'warning',
				content: getMultiLangByID('201201504A-000086') /*国际化处理：请计算租赁负债！*/
			});
			return false;
		}

		//阶梯租金标准
		let step_rent = form.getFormItemsValue(basicInfoForm, 'step_rent').value;
		if (step_rent) {
			let result = checkStepRentTable.call(this);
			if (!result) {
				return false;
			}
		}
	}

	let valid = true;
	//如果多账簿的情况下，用户不切换到报告账簿的情况下，将无法验证报告账簿的非空值，这里手动验证
	let fieldsRequired = metaUtil.getRequiredFieldByArea(this.props, financeForm);
	let accbooks = this.state.accbooks;
	if (accbooks && accbooks.length > 1) {
		for (let i = 1; i < accbooks.length; i++) {
			let { pk_accbook, accbookName } = accbooks[i];
			let assetvo = this.assetDataMap[pk_accbook];
			let emptyFields = new Set();
			fieldsRequired.map((field) => {
				let { values: { [field]: { value: assetvo_value } } } = assetvo;
				if (!assetvo_value) {
					valid = false;
					emptyFields.add(field);
				}
			});
			if (!valid) {
				// show error msg
				let emptyFieldsLabel = metaUtil.getFieldLabels(this.props, financeForm, emptyFields);
				let title = `[${accbookName}] ${getMultiLangByID('facommon-000015')}`;
				emptyFieldsLabel = emptyFieldsLabel.map((f) => `[${f}]`);
				showMessage(this.props, {
					content: `<div> ${title} </div><div> ${emptyFieldsLabel.join(', ')} </div>`,
					color: 'danger'
				});
			}
		}
	}

	if (!valid) {
		return false;
	}

	//过滤空行
	cardTable.filterEmptyRows(usedept_tab, [ 'pk_dept', 'usescale' ], 'include');
	cardTable.filterEmptyRows(subequip_tab, []); //这里第二个参数需要一个空数组

	//校验多使用部门页签
	let usedep_flag = form.getFormItemsValue(basicInfoForm, 'usedep_flag').value;
	if (usedep_flag) {
		// 表体必输校验
		let allRows = cardTable.getVisibleRows(usedept_tab);
		if (!allRows || allRows.length < 2) {
			showMessage(props, { content: getMultiLangByID('201201504A-000010'), color: 'warning' });
			return false;
		}
		checkResult = cardTable.checkTableRequired(usedept_tab);
		if (!checkResult) {
			return false;
		} else {
			//不允许重复
			let deptSet = new Set();
			let deptScaleSet = new Set();
			allRows.map((row) => {
				deptSet.add(row.values.pk_dept.value);
				deptScaleSet.add(row.values.usescale.value);
			});
			if (deptSet.size !== allRows.length) {
				showMessage(props, { content: getMultiLangByID('201201504A-000011'), color: 'danger' });
				return false;
			}
			let hasNegative = [ ...deptScaleSet ].some((n) => {
				return n < 0;
			});
			if (hasNegative) {
				showMessage(props, { content: getMultiLangByID('201201504A-000012'), color: 'danger' });
				return false;
			}
		}
		return true;
	}
	return true;
}

function doSaveAdd(that) {
	doSave(that, true);
}

//保存单据
function doSave(that, isSaveAdd = false, hasGetInitSysparam = false, ischeckLrzx = false) {

	//先判断是否需要检验利润中心是否为空
	if(!hasGetInitSysparam){//没执行过查询业务参数
		let data = {
			pk_org : ORGID.GLOBLE,
			param : SYSINIT.FA_LRZX_CHECKNULL
		};
		ajax({
			url: '/nccloud/mmbd/pub/getsysinit.do',
			data: data,
			success: (res) => {
				hasGetInitSysparam = true;
				if('Y' == res.data[SYSINIT.FA_LRZX_CHECKNULL]){
					ischeckLrzx = true;
				}
				
				doSave(that, isSaveAdd, hasGetInitSysparam, ischeckLrzx);
			}
		});

		return;
	}

	const { props: { modal } } = that;
	if (!saveBefore.call(that)) {
		return;
	}

	//组装用于提交到后台的数据
	that.syncDataForCommit();

	let url = URL.SAVE; //新增保存
	if (that.props.getUrlParam('status') === UISTATE.EDIT) {
		url = URL.UPDATE; //修改保存
	}

	//保存需要的辅助参数
	let paramMap = that.getAssitParam();
	const { basicInfoData: { values: { pk_card: { value: pk_card } } } } = that;
	let isCategoryChanged = pk_card ? paramMap[pk_card]['editCategoryWhenUpdate'] : false;

	//获取多使用部门数据
	let usedeptData = getCardtableData.call(that, usedept_tab);
	//后台是先删除之前的然后再重新插入
	usedeptData = filterDeletedRows(usedeptData);
	
	let lrzxData = getCardtableData.call(that, lrzx_tab);

	if(lrzxData != undefined && lrzxData.length > 0){
		let ntotalfp = 0;
		lrzxData.forEach(function(indata){
			if('3' != indata.status){
				ntotalfp = parseFloat(ntotalfp)+ parseFloat(indata.values.usescale.value);
			}
		});

		if(ntotalfp != 100){
			toast({content:'利润中心部门子表比例加起来必须为100%',color:'danger'});//错误消息
			return;
		}
	}else{
		if(ischeckLrzx){
			toast({content:'利润中心部门不能为空',color:'danger'});//错误消息
			return;
		}
		
	}

	//获取 附属设备数据
	let subequipData = getCardtableData.call(that, subequip_tab);

	//获取使用权相关数据
	let usufructAssetAllDatas = getUsufructAssetAllDatas.call(that);

	let assetvos = Object.values(that.assetDataMap);

	//清除模拟折旧数据
	// 如果卡片新增模拟折旧或者是该账簿可以修改，那么清空当月计提的数据
	const status = that.props.getUrlParam('status');
	for (let assetvo of assetvos) {
		const { values: { pk_accbook: { value: pk_accbook } } } = assetvo;
		if (status === UISTATE.ADD || (that.editAbleBook && that.editAbleBook.includes(pk_accbook))) {
			assetvo.values.deprate = { value: 0, display: 0 };
			assetvo.values.depamount = { value: 0, display: 0 };
		}

		//编辑态 && editCategoryWhenUpdate=false, 回写历史表主键（在建卡日期多次改变中丢失）
		if (status === UISTATE.EDIT && !isCategoryChanged) {
			const { assetDataMapBack: { [pk_accbook]: { values: { pk_cardhistory } } } } = that;
			assetvo.values.pk_cardhistory = pk_cardhistory;
		}
	}

	//判断是否是类别变化
	if (that.props.getUrlParam('status') === UISTATE.EDIT) {
		if (isCategoryChanged) {
			for (let assetvo of assetvos) {
				assetvo.status = DATA_STATUS.NEW;
			}
		}
	}

	//预算控制
	if (that.budgetStrategy) {
		Object.assign(paramMap[pk_card], that.budgetStrategy);
	}

	//组装提交数据：按照一主多子的格式
	let data = {
		pageid: that.state.pageCode,
		templateid: that.templateid,
		userjson: paramMap,
		heads: [
			{
				pageid: that.state.pageCode,
				model: {
					areacode: assetAllArea,
					areaType: 'table',
					rows: assetvos
				}
			}
		],
		bodysMap: {
			[usedept_tab]: {
				pageid: that.state.pageCode,
				model: {
					areacode: usedept_tab,
					rows: usedeptData,
					areaType: 'table'
				}
			},
			[lrzx_tab]: {
				pageid: that.state.pageCode,
				model: {
					areacode: lrzx_tab,
					rows: lrzxData,
					areaType: 'table'
				}
			},
			[subequip_tab]: {
				pageid: that.state.pageCode,
				model: {
					areacode: subequip_tab,
					rows: subequipData,
					areaType: 'table'
				}
			},
			[usufructassetForm]: {
				pageid: that.state.pageCode,
				model: {
					areacode: usufructassetForm,
					rows: usufructAssetAllDatas.usufructassetFormValue,
					areaType: 'table'
				}
			},
			[rentpayplan_tab]: {
				pageid: that.state.pageCode,
				model: {
					areacode: rentpayplan_tab,
					rows: usufructAssetAllDatas.rentpayplanValue,
					areaType: 'table'
				}
			},
			[depaccrual_tab]: {
				pageid: that.state.pageCode,
				model: {
					areacode: depaccrual_tab_month, //虽然计提明细有按月和按天两个模板，但元数据是同一个，所以就按month的来进行翻译处理
					rows: usufructAssetAllDatas.depaccrualValue,
					areaType: 'table'
				}
			},
			[steprentstandard_tab]: {
				pageid: that.state.pageCode,
				model: {
					areacode: steprentstandard_tab,
					rows: usufructAssetAllDatas.steprentstandardValue,
					areaType: 'table'
				}
			}
		}
	};

	// 保存前验证回调
	let validateToSaveCallback = () => {
		ajax({
			url,
			data,
			success: (res) => {
				let { success, data } = res;
				if (success && data) {
					let { BudgetMessage } = data; //预算控制消息
					if (BudgetMessage) {
						modal.show(MODAL_ID.ConfirmModal, {
							title: getMultiLangByID('201201504A-000053') /* 国际化：'提示'*/,
							content: BudgetMessage,
							beSureBtnClick: () => {
								that.budgetStrategy = { SkipCodes: 'Y' };
								doSave(that, isSaveAdd);
							}
						});
					} else {
						showMessage(that.props, { type: MsgConst.Type.SaveSuccess });
						saveAfter(that, data, isSaveAdd, isCategoryChanged);
					}
				}
			},
			error: (err) => {
				showErrorMessageByRes(that.props, err);
			}
		});
	};

	//保存前执行验证公式:只支持【基本信息】区域的验证
	that.props.validateToSave(
		{
			pageid: that.state.pageCode,
			model: {
				areacode: basicInfoForm,
				rows: assetvos
			}
		},
		validateToSaveCallback,
		null,
		'form'
	);
}

function saveAfter(that, data, isSaveAdd = false, isCategoryChanged = false, isLeaseChange = false) {
	const { props: { cardTable, form } } = that;
	//1、更新缓存数据
	const status = that.props.getUrlParam('status');
	if (status === UISTATE.EDIT || isLeaseChange) {
		//编辑 -> 保存成功
		// 解锁卡片
		lockcards.call(that, 'unlock');
		if (isCategoryChanged) {
			//是修改了资产类别，先删除缓存再新增缓存
			let assetvos_bak = Object.values(that.assetDataMapBack);
			let pk_cardhistorys_bak = assetvos_bak.map((assetvo) => assetvo.values.pk_cardhistory.value);
			let pk_card = that.getHeadAttributeValue(data, 'pk_card');
			let delData = { pk_card, pk_cardhistorys: pk_cardhistorys_bak };
			that.updateAssetCache(delData, 'del');
			that.updateAssetCache(data, 'add');
		} else {
			//直接更新缓存
			that.updateAssetCache(data, 'update');
		}
	} else {
		//新增保存成功
		//更新缓存
		that.updateAssetCache(data, 'add');
	}

	if (isSaveAdd) {
		//【保存新增】按钮
		that.props.setUrlParam({ id: '' });
		that.resetOnAdd();
		setStatus.call(that, that.props, UISTATE.ADD);

		//展开表体
		cardTable.toggleCardTable([ subequip_tab, usedept_tab ], true);

		let { heads: [ { assetAll: { rows: [ { values: rows_values } ] } } ] } = data;
		const { pk_org_v, pk_org } = rows_values;
		form.setFormItemsValue(basicInfoForm, {
			pk_org_v,
			pk_org
		});

		afterEvent.call(that, that.props, basicInfoForm, 'pk_org', pk_org);
	} else {
		const pk_cardhistory = that.getHeadAttributeValue(data, 'pk_cardhistory');
		that.props.setUrlParam({
			status: UISTATE.BROWSE,
			id: pk_cardhistory
		});
		// 清空过期数据
		that.resetOnAdd();
		//2、更新界面数据
		that.setValue(data);
		setStatus.call(that, that.props);
	}
}

function doCopy(that) {
	const { props: { cardPagination } } = that;
	let pk_card = that.getPkcardFromUrl();
	that.facardCopy.showCopyCardDialog(that, pk_card);
	that.facardCopy.setCopySuccessAfter((pk) => {
		//加载复制成功的最后一条数据
		pageInfoClick.call(that, that.props, pk);

		// 设置翻页控件当前id
		cardPagination.setCardPaginationId({ id: pk });
	});
}

/**
 * 修改按钮
 *
 * //更新的时候需要获取的数据
 *       this.depmethodFormulaFieldMap = {}; //折旧方法公式字段
 *       this.depmethods = [];//折旧方法列表
 *       this.fa10param = {};//FA10 参数<pk_accbook, boolean>
 *       this.accbookCurrency = {};//账簿币种
 *       this.is_allow_dept_midlev = false;
 *
 * @param that
 * @returns {Promise<any>}
 */
function doEdit(that) {
	const { props: { form } } = that;
	//编辑之前
	that.editAbleBook = [];
	that.editCategoryWhenUpdate = false;
	that.budgetStrategy = null;

	//日期类型字段恢复可编辑
	form.setFormItemsDisabled(basicInfoForm, {
		business_date: false,
		begin_date: false,
		close_date: false
	});
	if (that.state.financeShowFlag) {
		form.setFormItemsDisabled(financeForm, {
			dep_start_date: false,
			dep_end_date: false
		});
	}

	//卡片校验通过，可以编辑
	let locking = (resData) => {
		/* 对卡片进行加锁 */
		lockcards.call(that, 'lock').then(
			() => {
				editPostProcessing.call(that, resData);
				setStatus.call(that, that.props, UISTATE.EDIT);
				that.forceUpdate();
			},
			() => {
				setStatus.call(that, that.props, UISTATE.BROWSE);
			}
		);
	};

	/* 编辑预检查 */
	return editPreCheck.call(that).then(locking, (err) => {
		showMessage(that.props, {
			content: (err && err.message) || err || getMultiLangByID('201201504A-000013'),
			color: 'danger'
		});
		setStatus.call(that, that.props, UISTATE.BROWSE);
	});
}

/* 编辑后处理 */
function editPostProcessing(resData) {
	const { props: { form, button, cardTable } } = this;

	//修改时 将卡片数据更新为月初数据
	let { monthBeginvos, MonthBeginFieldsWhenEdit } = resData;
	if (monthBeginvos) {
		monthBeginvos.map((beginVO) => {
			let accbook = beginVO.pk_accbook;
			let assetVO = this.assetDataMap[accbook];
			MonthBeginFieldsWhenEdit.map((field) => {
				assetVO.values[field].value = beginVO[field];
			});
		});

		//更新界面数据
		const { state: { financeShowFlag, currentPkaccbook: pkaccbook } } = this;
         	const accbookData4Form = this.wrapAccbookData(pkaccbook);
         	const basicInfoData4Form = this.wrapBasicInfoData();
		if (financeShowFlag) {
			form.setAllFormValue({
				[basicInfoForm]: basicInfoData4Form,
				[financeForm]: accbookData4Form
			});
		} else {
			form.setAllFormValue({
				[basicInfoForm]: basicInfoData4Form
			});
		}
	}

	//更新工作量字段的编辑性
	const accbookData = this.wrapAccbookData(this.state.currentPkaccbook);
	updateDeptmethodItem.call(this, this.props, accbookData);

	//更新【资产组】参照
	updateAssetGroupItem(this.props, !this.isHeadAssetFinanceorg);
}

/* 编辑前检查 */
function editPreCheck() {
	let that = this;
	//获取当前账簿的数据, 没有选中的账簿时直接返回
	const { state: { currentPkaccbook } } = that;
	const assetvo = that.getAccbookDataByPkaccbook(currentPkaccbook);
	const { values: { pk_card: { value: pk_card } } } = assetvo;

	return new Promise((resolve, reject) => {
		ajax({
			url: URL.EDIT,
			data: {
				pk: pk_card,
				resourceCode: '2012016030' //固定资产卡片维护和原始卡片走同一个资源号
			},
			success: (res) => {
				let { success, data } = res;
				if (success) {
					let isValidate = data['validate'];
					let failure = data['failure'];

					if (failure) {
						reject(failure);
						return;
					}

					if (!isValidate) {
						reject();
						return;
					}

					that.editAbleBook = data['editAbleBook'];
					Object.assign(that.relativeData, data['relativeData']);
					let paramVO = data['paramVO'];
					that.setFAParam(paramVO);
					setFAParamStatus.call(that, paramVO);
					resolve(data);
				}
			},
			error: (err) => {
				reject(err);
			}
		});
	});
}

/**
 * 设置FA组织参数状态
 * 
 * @param {FA组织级参数} paramVO 
 */
function setFAParamStatus(paramVO) {
	const { props: { cardTable } } = this;

	let { is_allow_dept_midlev, depmethodFormulaFieldMap, depmethods, org_digit, isHeadAssetFinanceorg } = paramVO;
	this.depmethodFormulaFieldMap = depmethodFormulaFieldMap; //折旧方法公式字段
	this.depmethods = depmethods; //折旧方法列表

	//更新部门是否能够选择非末级
	updateDeptRefLevel(this, is_allow_dept_midlev);

	//更新【资产组】参照
	updateAssetGroupItem(this.props, !isHeadAssetFinanceorg);

	// 设置附属设备页签的精度，新增的时候没有编辑后事件，所以在这里设置一下
	cardTable.setColScale([ { areacode: subequip_tab, fieldcode: 'originvalue', scale: org_digit } ]);

	// 更新精度
	this.updateScale();
}

//删除单据
function doDelete(that) {
	const { props: { form } } = that;
	if (doDeleteBeforeCheck(that)) {
		return;
	}

	let pk_cardhistorys = [];
	for (let pk_accbook in that.assetDataMap) {
		let assetvo = that.assetDataMap[pk_accbook];
		let { values: { pk_cardhistory: { value: pk_cardhistory } } } = assetvo;
		pk_cardhistorys.push(pk_cardhistory);
	}

	const pk = that.getPkcardFromUrl();
	if (pk) {
		const ts = form.getFormItemsValue(basicInfoForm, 'ts').value;
		const data = {
			pks: pk,
			tss: ts,
			uitype: 'card'
		};
		ajax({
			url: URL.DELETE,
			data,
			success: (res) => {
				let { success, data } = res;
				if (success) {
					let { allSuccess, message, suceessArr, failure } = data;
					if (failure) {
						showMessage(that.props, { content: failure, color: 'danger' });
					} else if (allSuccess) {
						/*国际化处理：删除成功*/
						showMessage(that.props, { type: MsgConst.Type.DeleteSuccess });
						let delData = { pk_card: pk, pk_cardhistorys };
						deleteAfter.call(that, delData);
					} else {
						if (message && message.length === 1) {
							toast({ content: message[0], color: 'danger' });
						} else {
							toast({
								duration: 'infinity',
								color: 'danger',
								content: message.shift(),
								groupOperation: true,
								groupOperationMsg: message,
								TextArr: [
									getMultiLangByID('amcommon-000005'),
									getMultiLangByID('amcommon-000006'),
									getMultiLangByID('amcommon-000007')
								] /* 国际化处理： ['展开', '收起', '关闭'] */
							});
						}
					}
				} else {
					/*国际化处理：删除失败*/
					showMessage(that.props, { type: MsgConst.Type.DeleteFailed });
				}
			},
			error: (err) => {
				showErrorMessageByRes(that.props, err);
			}
		});
	}
}

//删除单据前检查
function doDeleteBeforeCheck(that) {
	const { props: { form, pageConfig } } = that;
	const source = form.getFormItemsValue(basicInfoForm, 'bill_source').value;
	let error = '';
	if (source === BILL_SOURCE_TYPES.conbin_src) {
		//合并生成卡片,不能删除
		error = getMultiLangByID('201201504A-000014') /* 国际化处理： 合并生成卡片,不能删除*/;
	} else if (source === BILL_SOURCE_TYPES.split_src) {
		// 拆分卡片,不能删除
		error = getMultiLangByID('201201504A-000015') /* 国际化处理： 拆分卡片,不能删除*/;
	} else if (source === BILL_SOURCE_TYPES.deploy_in_src) {
		// 调拨增加资产，不能删除
		error = getMultiLangByID('201201504A-000016') /* 国际化处理： 调拨增加资产,不能删除*/;
	} else {
		const { newasset_flag } = pageConfig;
		if (newasset_flag > ASSET_ADDED_WAY.isNew) {
			//非当月增加，不能删除
			error = getMultiLangByID('201201504A-000017') /* 国际化处理： 非当月增加，不能删除*/;
		}
	}

	if (error) {
		showMessage(that.props, { content: error, color: 'danger' });
	}

	return error;
}

//删除成功后
function deleteAfter(delData) {
	//删除成功
	//根据当前id,获取下个id
	let id = this.props.getUrlParam('id');
	let nextId = getNextId.call(this, id);

	//调用删除缓存数据方法（需要同时删除 allpks 和 列表态表格中的数据）
	this.updateAssetCache(delData, 'del');

	//加载下一条数据
	pageInfoClick.call(this, this.props, nextId);
}

//获取下一个卡片的ID, （仅供删除卡片后获取下一个 pk_card 使用）
function getNextId(currId) {
	//根据当前id,获取下个id
	let nextId = cardCache.getNextId(currId, assetDataSource);
	this.props.setUrlParam({ id: nextId });
	if (nextId) {
		let pk_card_next = this.getPkcardFromUrl();

		if (pk_card_next != this.curr_pk_card) {
			return nextId;
		} else {
			//多账簿情况下：新增一个卡片->删除卡片后，getNextId 会出现递归死循环（具体见平台 cardCache.getNextId）
			cardCache.deleteCacheById('pk_cardhistory', currId, assetDataSource);
			return getNextId.call(this, nextId);
		}
	}
	return null;
}

function doCancel(that) {
	const { props: { form, cardTable, getUrlParam, setUrlParam, cardPagination } } = that;
	const status = getUrlParam('status');
	if (status === UISTATE.ADD) {
		//新增 --> 取消
		// 加载编辑前数据，如果编辑前没有数据，则加载当前列表最后一条数据，如果还没有，显示为空不处理
		let id = cardCache.getCurrentId(assetDataSource);
		if (!id) {
			id = cardCache.getCurrentLastId(assetDataSource);
		}
		// 设置翻页控件当前id
		cardPagination.setCardPaginationId({ id });
		pageInfoClick.call(that, that.props, id);
	} else {
		//修改 --> 取消
		// 解锁卡片
		lockcards.call(that, 'unlock');

		setUrlParam({ status: UISTATE.BROWSE });
		form.cancel(basicInfoForm);
		if (that.state.financeShowFlag) {
			form.cancel(financeForm);
		}

		//恢复页签数据
		[ usedept_tab, subequip_tab ].forEach((tab) => {
			cardTable.resetTableData(tab);
		});

		//收起表体页签
		cardTable.toggleCardTable(TabsHideDefault, false);

		that.resetOnAdd();
		doRefresh(that);
	}
}

//刷新界面
function doRefresh(that) {
	let pk_card = that.getPkcardFromUrl();

	// 清空过期数据
	that.resetOnAdd();

	new Promise(function(resolve, reject) {
		resolve(that.getData(pk_card));
	}).then(
		(data) => {
			if (data) {
				/*国际化处理：刷新成功*/
				showMessage(that.props, { type: MsgConst.Type.RefreshSuccess });
				that.getDataBack(data);
			}
		},
		() => {
			// 未查询到数据，清除界面
			setStatus.call(that, that.props, UISTATE.BLANK);
		}
	);
}

function doPrintChild(that) {
	let nodekey = '201201504A_child';
	doPrint(that, nodekey);
}

function doPrintNoChild(that) {
	let nodekey = '201201504A_nochild';
	doPrint(that, nodekey);
}

function doPrint(that, nodekey) {
	let printData = getPrintData.call(that, that.props, 'print');
	printData.nodekey = nodekey || printData.nodekey;
	if (!printData) {
		/*国际化处理：请选择需要打印的数据*/
		showMessage(that.props, { type: MsgConst.Type.ChoosePrint });
		return;
	}
	print(
		'pdf', // 支持两类：'html'为模板打印，'pdf'为pdf打印
		URL.PRINT_CARD, // 后台打印服务url
		printData
	);
}

function doOutput(that) {
	let printData = getPrintData.call(that, that.props, 'output');
	//输出默认为不带副卡的模板
	printData.nodekey = '201201504A_nochild';
	if (!printData) {
		/*国际化处理：请选择需要输出的数据*/
		showMessage(that.props, { type: MsgConst.Type.ChooseOutput });
		return;
	}

	output({
		url: URL.PRINT_CARD,
		data: printData
	});
}

/*
 * 获取打印数据
 */
function getPrintData(props, outputType = 'print') {
	const { pageConfig } = this.props;
	let printNodekey = null;

	let pk_card = this.curr_pk_card;
	if (!pk_card) {
		return;
	}

	let {
		state: { currentPkaccbook: pk_accbook },
		basicInfoData: {
			values: { period: { value: period }, accyear: { value: accyear }, pk_cardhistory: { value: pk_cardhistory } }
		}
	} = this;

	let obj = {
		pk_cardhistory,
		pk_card,
		period,
		accyear,
		pk_accbook
	};

	let pks = [ JSON.stringify(obj) ];
	let printData = {
		filename: pageConfig.title, // 文件名称
		nodekey: printNodekey, // 模板节点标识
		oids: pks, // 需要打印数据主键
		outputType // 输出类型
	};
	return printData;
}

function linkToList(props, param = {}) {
	let defaultParam = {
		pagecode: PAGE_CODE.LIST
	};
	props.pushTo('/list', Object.assign(defaultParam, param));
}

//获取 cardTable 的数据
function getCardtableData(areacode, exceptKeys = []) {
	const { props: { cardTable } } = this;
	if (areacode == depaccrual_tab) {
		return this.getDepaccrualCache().rows;
	} else {
		//过滤空行
		cardTable.filterEmptyRows(areacode, exceptKeys);
		return cardTable.getAllRows(areacode);
	}
}

//获取使用权资产相关数据
function getUsufructAssetAllDatas() {
	const { props: { getUrlParam, form, cardTable } } = this;
	const status = getUrlParam('status');
	const usufructasset_flag = form.getFormItemsValue(basicInfoForm, 'usufructasset_flag').value;
	if (!usufructasset_flag) {
		return {};
	}
	let usufructasset_flag_back = false;
	if (status === UISTATE.EDIT) {
		const {
			assetDataMapBack: {
				[this.state.currentPkaccbook]: { values: { usufructasset_flag: { value: usufructasset_flag_old } } }
			}
		} = this;
		usufructasset_flag_back = usufructasset_flag_old;
	}
	//使用权资产
	let usufructassetFormValue = (usufructasset_flag && getUsufructAssetTab.call(this)) || [];
	//租金付款计划
	let rentpayplanValue = (usufructasset_flag && getCardtableData.call(this, rentpayplan_tab)) || [];
	//阶梯租金标准
	let steprentstandardValue = (usufructasset_flag && getCardtableData.call(this, steprentstandard_tab)) || [];
	//计提利息明细
	let depaccrualValue = (usufructasset_flag && getCardtableData.call(this, depaccrual_tab)) || [];

	// 固定资产卡片 -> 使用权资产卡片
	if (UISTATE.EDIT == status && usufructasset_flag != usufructasset_flag_back) {
		updateVOStatus(usufructassetFormValue);
	}
	return { usufructassetFormValue, rentpayplanValue, steprentstandardValue, depaccrualValue };
}

/**
 * 更新使用权卡片的vo状态 VOStatus {UNCHANGED = 0;UPDATED = 1;NEW = 2;DELETED = 3;}
 */
function updateVOStatus(tab) {
	if (tab) {
		tab.forEach((vo) => {
			vo.status = VOSTATUS.NEW;
		});
	}
}

//过滤掉已删除的数据
function filterDeletedRows(rows) {
	let newrows = rows;
	if (rows && rows.length) {
		newrows = rows.filter((r) => r.status != DATA_STATUS.DELETED);
	}
	return newrows;
}

//模拟折旧
function doSimulateDep(that) {
	if (!doSimulateBefore(that)) {
		return;
	}

	doCurrentAccbookEdit(that, URL.simulateDep, () => {
		/*国际化处理：模拟折旧成功*/
		showMessage(that.props, { content: getMultiLangByID('201201504A-000018'), color: 'success' });
	});
}

//模拟累计折旧
function doSimulateAccudep(that) {
	if (!doSimulateBefore(that)) {
		return;
	}

	doCurrentAccbookEdit(that, URL.simulateAccuDep, () => {
		/*国际化处理：模拟累计折旧成功*/
		showMessage(that.props, { content: getMultiLangByID('201201504A-000019'), color: 'success' });
	});
}

//模拟折旧、模拟累计折旧前校验
function doSimulateBefore(that) {
	const { props } = that;
	//1、非空校验
	if (!checkNull.call(that)) {
		return false;
	}

	if (!that.isAllowChangeHeadWhenEdit()) {
         	/* "201201504A-0000112": "当前账簿已经有后续操作，不能模拟！" */
         	showMessage(props, { content: getMultiLangByID('201201504A-0000112'), color: 'danger' });
		return;
	}

	//组装用于提交到后台的数据
	that.syncDataForCommit();
	return true;
}

//当前账簿的编辑
function doCurrentAccbookEdit(that, url, successBack, errorBack) {
	const { props: { form } } = that;
	const { state: { pageCode, currentPkaccbook } } = that;
	//获取当前账簿的数据, 没有选中的账簿时直接返回
	if (!currentPkaccbook) {
		return;
	}

	const assetvo = that.getAccbookDataByPkaccbook(currentPkaccbook);

	let data = {
		grid: {
			pageid: pageCode,
			templetid: that.templateid,
			model: {
				areacode: assetAllArea,
				areaType: 'table',
				rows: [ assetvo ]
			}
		}
	};

	ajax({
		url,
		data,
		success: (res) => {
			let { success, data } = res;
			if (success && data && data.heads) {
				let assetAllData = [];
				data.heads.forEach((head) => {
					if (head.assetAll && head.assetAll.rows && head.assetAll.rows.length > 0) {
						assetAllData = assetAllData.concat(head.assetAll.rows);
					}
				});

				//更新界面数据
				that.assetDataMap[currentPkaccbook] = assetAllData[0];
				//设置基本区域form的值
				that.basicInfoData = that.assetDataMap[currentPkaccbook];
				const basicInfoData4Form = that.wrapBasicInfoData();
				// 设置财务区的值
				const accbookData4Form = that.wrapAccbookData(currentPkaccbook);

				//财务区域未展开，展开财务区
				if (!that.state.financeShowFlag) {
					that.setState({
						financeShowFlag: true
					});
				}

				let formValueObj = {};
				if (basicInfoData4Form) {
					formValueObj[basicInfoForm] = basicInfoData4Form;
				}
				if (accbookData4Form && that.state.financeShowFlag) {
					formValueObj[financeForm] = accbookData4Form;
				}
				form.setAllFormValue(formValueObj);

				if (successBack && isFunction(successBack)) {
					successBack(assetAllData[0]);
				}
			} else {
				/*国际化处理：返回数据格式错误！*/
				showMessage(that.props, { content: getMultiLangByID('201201504A-000004'), color: 'danger' });
			}
		},
		error: (err) => {
			showMessage(that.props, { color: 'danger', content: err.message });
			if (errorBack && isFunction(errorBack)) {
				errorBack();
			}
		}
	});
}

/**
 * 加锁，解锁卡片
 */
function lockcards(lockflag, async = true) {
	let cuserid = getContext(loginContextKeys.userId, assetDataSource);
	let dataSourceOfServer = getContext(loginContextKeys.dataSourceCode, assetDataSource);

	let pk_card = this.getPkcardFromUrl();
	if (!pk_card) {
		return;
	}
	let allpks = [ pk_card ];
	let param = {
		allpks,
		msgMap: {
			usrid: cuserid,
			lockflag,
			dSource: dataSourceOfServer
		}
	};
	return lockrequest.call(this, param, async);
}

/**
 * 加解锁请求
 * @param {*} param
 * @param async
 */
function lockrequest(param, async = true) {
	let promise = new Promise(function(resolve, reject) {
		ajax({
			url: URL.LockOrUnlockCard,
			data: param,
			async,
			success: (res) => {
				resolve();
			},
			error: (res) => {
				if (res && res.message) {
					showMessage(null, { content: res.message, color: 'danger' });
				}
				reject();
			}
		});
	});

	return promise;
}

//联查设备卡片
function queryAboutCard(props) {
	// const pk_equip = props.form.getFormItemsValue(basicInfoForm, 'pk_equip').value;
	// if (pk_equip) {
	// 	openEquipCardByPk(props, pk_equip);
	// } else {
	// 	/*国际化处理：选中的数据中第一条没有关联设备卡片！*/
	// 	showMessage(props, { content: getMultiLangByID('201201504A-000020'), color: 'warning' });
	// }

	const pk_equip = props.form.getFormItemsValue(basicInfoForm, 'pk_equip').value;
	if (pk_equip) {
		const pk_card = props.form.getFormItemsValue(basicInfoForm, 'pk_card').value;
		openEquipCardByFaCardPk(props, pk_card);
	} else {
		/*国际化处理：选中的数据中第一条没有关联设备卡片！*/
		showMessage(props, { content: getMultiLangByID('201201504A-000020'), color: 'warning' });
	}
}

/**
 * 附件上传
 * @param  props
 */
function attachment(props) {
	//资产编码, 卡片主键
	let billId = props.form.getFormItemsValue(basicInfoForm, 'pk_card').value;
	ncUploaderShow.call(this, 'uploader', {
		billId: 'fa/card/' + billId
	});
}

//影像扫描
function faReceiptScan(props) {
	cardFaImageScan(props, getReceiptData(props));
}

//影像查看
function faReceiptShow(props) {
	cardFaImageView(props, getReceiptData(props));
}

//组装影像数据
function getReceiptData(props) {
	const { form: { getFormItemsValue } } = props;
	let pk_card = getFormItemsValue(basicInfoForm, 'pk_card').value;
	let billtype = getFormItemsValue(basicInfoForm, 'bill_type').value;
	let transi_type = getFormItemsValue(basicInfoForm, 'transi_type').value;
	let pk_org = getFormItemsValue(basicInfoForm, 'pk_org');
	let billmaketime = getFormItemsValue(basicInfoForm, 'billmaketime').value;
	let billmaker = getFormItemsValue(basicInfoForm, 'billmaker').value;
	let card_code = getFormItemsValue(basicInfoForm, 'card_code').value;

	return {
		pk_billid: pk_card,
		pk_billtype: billtype,
		pk_tradetype: transi_type,
		pk_org: pk_org.value,
		OrgNo: pk_org.value,
		pk_card: pk_card,
		BillType: transi_type,
		BillDate: billmaketime,
		Busi_Serial_No: pk_card,
		userid: billmaker,
		BillCode: card_code,
		OrgName: pk_org.display
	};
}

//单据追溯
function billreview() {
	const { props: { form } } = this;

	//获取卡片来源交易类型 有默认值handin
	let transi_type_source = form.getFormItemsValue(basicInfoForm, 'transi_type_source').value;
	if (transi_type_source === BILL_SOURCE_TYPES.handin_src) {
		transi_type_source = null;
	}

	// 获取卡片来源单据类型
	const bill_source = form.getFormItemsValue(basicInfoForm, 'bill_source').value;
	// const asset_state = form.getFormItemsValue(basicInfoForm, 'asset_state').value;
	//获取主键
	let pk_src = form.getFormItemsValue(basicInfoForm, 'pk_bill_src').value;

	let type_src = transi_type_source || bill_source;

	if (type_src !== BILL_SOURCE_TYPES.handin_src) {
		if (pk_src && type_src && !type_src.startsWith(BILL_SOURCE_TYPES.equip_src)) {
			CardLinkToBill.call(this, this.props, pk_src, type_src);
		} else {
			/*国际化处理：该单据的来源单据号错误*/
			showMessage(this.props, { content: getMultiLangByID('201201504A-000021'), color: 'warning' });
		}
	} else {
		/*国际化处理：该单据没有来源单据*/
		showMessage(this.props, { content: getMultiLangByID('201201504A-000022'), color: 'warning' });
	}
}

//联查业务凭证
function faBillQueryAboutVoucher(that) {
	const { props: { form, pageConfig } } = that;
	let linkCacheWord = '_LinkVouchar'; // 联查凭证标识

	let result = getCheckedAreaRow(that.props);

	if (result) {
		//选择的行数据
		let checkRow = result.rows[0].data;
		//选择的页签的主键字段
		let pkFiled = result.pkFiled;
		//选择的行数据主键
		let { values: { [pkFiled]: { value: pk_bill } } } = checkRow;
		//当前单据类型
		let { values: { bill_type: { value: bill_type } } } = checkRow;

		let pk_org = form.getFormItemsValue(basicInfoForm, 'pk_org').value;
		let pk_group = form.getFormItemsValue(basicInfoForm, 'pk_group').value;
		//let pk_accbook = props.form.getFormItemsValue(constants.AREA.CARD.BASIC_INFO_AREA,'pk_accbook').value;
		let pk_accbook = that.state.currentPkaccbook;

		let dataArray = getLinkData(pk_bill, bill_type, pk_org, pk_group, pk_accbook);

		// 命名格式为 appid_LinkVouchar,其中appid为自己小应用的应用编码
		let appId_LinkVouchar = pageConfig.appid + linkCacheWord;
		openToVouchar(that.props, appId_LinkVouchar, dataArray);
	}
}

function getLinkData(pk_bill, bill_type, pk_org, pk_group, pk_accbook) {
	let dataArray = [];

	let queryRelationIDUrl = URL.QueryResourceid;

	//不需要特殊联查的单据
	let billtypeNoLink = [
		'HQ', //减值准备
		'HE' //评估单据
	];

	let relationIDs = [];
	if (bill_type.indexOf('H') != 0 || billtypeNoLink.indexOf(bill_type) != -1) {
		relationIDs.push(pk_bill);
	} else {
		//变动单取前20位为主键
		if (bill_type.substring(0, 2) == 'HG') {
			pk_bill = pk_bill.substring(0, 20);
		}

		//其余单据走接口查询
		//接口参数
		let urlData = {
			bill_type: bill_type,
			pk_org: pk_org,
			pk_bill: pk_bill,
			pk_accbook: pk_accbook,
			pk_group: pk_group
		};
		ajax({
			url: queryRelationIDUrl,
			data: urlData,
			async: false,
			success: (res) => {
				if (res && res.data) {
					relationIDs = res.data;
				}
			},
			error: (res) => {
				if (res && res.message) {
					showMessage(null, { color: 'danger', content: res.message });
				}
			}
		});
	}

	for (let relationID of relationIDs) {
		let obj = {
			// pk_billtype 固定资产实际传入的是交易类型
			pk_billtype: null,
			relationID: relationID,
			pk_group: pk_group,
			pk_org: pk_org
		};
		dataArray.push(obj);
	}

	return dataArray;
}

//获取勾选的页签
function getCheckedAreaRow(props) {
	const { cardTable } = props;
	/** 表体行来源单据主键字段名 */
	const PK_BILL_Tab = 'pk_bill';

	let result;
	//变动页签
	let rows = cardTable.getCheckedRows(alter_tab);
	let pkFiled;
	if (rows && rows.length > 0) {
		pkFiled = PK_BILL_Tab;
		result = {
			rows,
			pkFiled
		};
		return result;
	}

	//评估页签
	rows = cardTable.getCheckedRows(evaluate_tab);
	if (rows && rows.length > 0) {
		pkFiled = PK_BILL_Tab;
		result = {
			rows,
			pkFiled
		};
		return result;
	}

	//减值页签
	rows = cardTable.getCheckedRows(devalue_tab);
	if (rows && rows.length > 0) {
		pkFiled = PK_BILL_Tab;
		result = {
			rows,
			pkFiled
		};
		return result;
	}

	//减少页签
	rows = cardTable.getCheckedRows(reduce_tab);
	if (rows && rows.length > 0) {
		pkFiled = PK_BILL_Tab;
		result = {
			rows,
			pkFiled
		};
		return result;
	}

	//调拨页签
	rows = cardTable.getCheckedRows(deploy_tab);
	if (rows && rows.length > 0) {
		pkFiled = PK_BILL_Tab;
		result = {
			rows,
			pkFiled
		};
		return result;
	}
	/*国际化处理：请选择页签中的一条记录*/
	showMessage(props, { content: getMultiLangByID('201201504A-000023'), color: 'danger' });
}

/**
 * 计算租赁负债
 * @returns 
 */
function calculateLeaseLiabilities() {
	const { props, props: { form, modal } } = this;

	if (this.bill_source_4A3A) {
		/* "201201504A-0000110": "资产租入的卡片不允许重新计算租赁负债！" */
		showMessage(props, { content: getMultiLangByID('201201504A-0000110'), color: 'danger' });
		return;
	}

	// 如果有后续操作不允许计算租赁负债
	if (!this.isAllowChangeHeadWhenEdit()) {
		/* "201201504A-000097": "存在后续操作不允许重新计算租赁负债！" */
		showMessage(props, { content: getMultiLangByID('201201504A-000097'), color: 'danger' });
		return;
	}
	// 租赁负债得计算忽略原币原值得必输项
	form.setFormItemsRequired(basicInfoForm, { originvalue: false });
	//计算租赁负债之前先做下非空等校验
	let success = usufructCheckBefore.call(this);
	form.setFormItemsRequired(basicInfoForm, { originvalue: true });
	if (!success) {
		return;
	}

	let data = assembleUsufructDatas.call(this);
	ajax({
		url: URL.LEASELIABILITIES,
		data,
		success: (res) => {
			let { success, data } = res;
			if (success && data) {
				//判断原值是否相同
				let originvalue = form.getFormItemsValue(basicInfoForm, 'originvalue').value;
				//没有原值则直接更新
				let { heads: [ { assetAll: { rows: [ { values: { originvalue: { value: originvalue0 } } } ] } } ] } = data;

				if (originvalue && originvalue0 != originvalue) {
					modal.show(MODAL_ID.LeaseLiabilitiesModal, {
						beSureBtnClick: beSureEvent.bind(this, data, true),
						cancelBtnClick: cancelEvent.bind(this, data),
						closeModalEve: closeEvent.bind(this, data)
					});
				} else {
					beSureEvent.call(this, data);
				}
			}
		}
	});
}

function beSureEvent(data, originvalueRelateFlag = false) {
	this.isNeedCalculateLeaseLiabilities = false;
	this.setValue(data);
	if (originvalueRelateFlag) {
		let { heads: [ { assetAll: { rows: [ { values: { originvalue: originvalueNew } } ] } } ] } = data;
		this.props.form.setFormItemsValue(basicInfoForm, { originvalue: originvalueNew });
		afterEvent.call(this, this.props, basicInfoForm, 'originvalue', originvalueNew, { value: null }, null, null, false);
	}
}

// 计算租赁负载结果提示取消时则不更新原值
function cancelEvent(data) {
	this.isNeedCalculateLeaseLiabilities = false;
	const { props: { form } } = this;
	const originvalue = form.getFormItemsValue(basicInfoForm, 'originvalue');
	data.heads.forEach(head => {
		head.assetAll.rows.forEach((it) => {
			it.values.originvalue.value = originvalue.value;
		});
	});
	this.setValue(data);
}

function closeEvent(data) {
	cancelEvent.call(this, data);
}

// 使用权相关必输项校验
function usufructCheckBefore() {
	const { props: { form } } = this;

	let usufructasset_flag = form.getFormItemsValue(basicInfoForm, 'usufructasset_flag').value;
	if (!usufructasset_flag) {
		return true;
	}

	//表头必输项校验
	let checkResult = form.isCheckNow([ basicInfoForm ]);
	if (!checkResult) {
		return false;
	}


	// 续租选择权
	let renewal_flag = form.getFormItemsValue(basicInfoForm, 'renewal_flag').value;
	if (renewal_flag) {
		//续租截止期
		let relet_ending_date = form.getFormItemsValue(basicInfoForm, 'relet_ending_date').value;
		if (!relet_ending_date) {
			toast({
				color: 'danger',
				content: getMultiLangByID('201201504A-000092') /*国际化处理：续租截止期不能为空 */
			});
			return false;
		}
	}
	// 购买选择权
	let purchase_choice = form.getFormItemsValue(basicInfoForm, 'purchase_choice').value;
	if (purchase_choice) {
		// 购买价格
		let purchase_price = form.getFormItemsValue(basicInfoForm, 'purchase_price').value;
		if (!purchase_price) {
			toast({
				color: 'danger',
				content: getMultiLangByID('201201504A-000093') /*国际化处理：购买价格不能为空 */
			});
			return false;
		}
	}

	// 资产类别
	let pk_category = form.getFormItemsValue(basicInfoForm, 'pk_category').value;
	if (!pk_category) {
		toast({
			color: 'danger',
			content: getMultiLangByID('201201504A-000096') /*国际化处理：资产类别不允许为空！ */
		});
		return false;
	}

    //阶梯租金标准
    let step_rent = form.getFormItemsValue(basicInfoForm, 'step_rent').value;
    if (step_rent) {
        let result = checkStepRentTable.call(this);
        if (!result) {
            return false;
        }
    }

     /* 衔接处理方法 */
     let cohesion_process = form.getFormItemsValue(basicInfoForm, 'cohesion_process').value;
 
     /* 追溯日期 */
     let retrospective_date = form.getFormItemsValue(basicInfoForm, 'retrospective_date').value;
     /* 简单追溯调整 */
     if(cohesion_process === '1'){
         if (!retrospective_date) {
             toast({
                 color: 'danger',
                 content: getMultiLangByID('201201504A-0000114') /*追溯日期不允许为空！ */
             });
             return false;
         }
         let input = moment(retrospective_date, 'YYYY-MM-DD HH:mm:ss');
         let limit = moment('2021-01-01 00:00:00', 'YYYY-MM-DD HH:mm:ss');
         if(input.isAfter(limit)){
             toast({
                 color: 'danger',
                 content: getMultiLangByID('201201504A-0000100') /*追溯日期不能晚于2021年01月01日！ */
             });
             return false;
         }
     }
 
     /* 租金拆分 */
     let rent_split_flag = form.getFormItemsValue(basicInfoForm, 'rent_split_flag').value;
     if(rent_split_flag === true){
         /* 拆分金额（含税） */
         let split_renttax = form.getFormItemsValue(basicInfoForm, 'split_renttax').value;
 
         if(!split_renttax){
             toast({
                 color: 'danger',
                 content: getMultiLangByID('201201504A-0000101') /*拆分金额（含税）不能为空！ */
             });
             return false;
         }
     }
 
	return true;
}

//组装使用权资产相关数据到后台---使用权相关的组装数据，只需要assetvo、usufructassetForm、steprentstandard_tab这三部分
function assembleUsufructDatas() {
	const { props: { form, cardTable } } = this;
	let allRows = cardTable.getAllRows(steprentstandard_tab);
	let allData = cardTable.getAllData(steprentstandard_tab);
	//组装用于提交到后台的数据
	this.syncDataForCommit();
	let assetvos = Object.values(this.assetDataMap);
	let userjson = {
		current_accbook: this.state.currentPkaccbook
	};
	//组装提交数据：按照一主多子的格式
	let data = {
		pageid: this.state.pageCode,
		templateid: this.templateid,
		userjson,
		heads: [
			{
				pageid: this.state.pageCode,
				model: {
					areacode: assetAllArea,
					areaType: 'table',
					rows: assetvos
				}
			}
		],
		bodysMap: {
			//使用权资产
			[usufructassetForm]: {
				pageid: this.state.pageCode,
				model: {
					areacode: usufructassetForm,
					rows: getUsufructAssetTab.call(this),
					areaType: 'table'
				}
			},
			//租金标准
			[steprentstandard_tab]: {
				pageid: this.state.pageCode,
				model: {
					areacode: steprentstandard_tab,
					rows: getCardtableData.call(this, steprentstandard_tab, [ 'start_date' ]),
					areaType: 'table'
				}
			}
		}
	};
	return data;
}

export {
	linkToList,
	lockcards,
	lockrequest,
	saveAfter,
	doRefresh,
	filterDeletedRows,
	getCardtableData,
	editPreCheck,
	setFAParamStatus
};

/*Hita0WssSbjpM+C19QDJ07Polf/ANXjrTbPQimCg5mSCg+tCWtORC5TxqS/esH2V*/